package com.wt.easyadmin.common.utils;

import java.util.Date;

import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

public class JwtUtil {
	
	private static final Logger log = LoggerFactory.getLogger(JwtUtil.class);

    /**
     * 过期时间60分钟
     */
    private static final long EXPIRE_TIME = 60 * 60 * 1000;
    
    /**
     * 过期刷新token时间
     */
    private static final long REFRESH_TOKEN_TIME = 59 * 60 * 1000;
    /**
     * jwt 密钥
     */
    private static final String SECRET = "jwt_secret";

    /**
     * 生成签名
     * @param userId
     * @return
     */
    public static String sign(String userId) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    // 将 user id 保存到 token 里面
                    .withAudience(userId)
                    // 过期时间
                    .withExpiresAt(date)
                    // token 的密钥
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据token获取userId
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        try {
            String userId = JWT.decode(token).getAudience().get(0);
            return userId;
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static boolean checkSign(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    // .withClaim("username", username)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            long a = jwt.getExpiresAt().getTime()-(new Date()).getTime();
            //jwt.getClaim("1");
            log.info("jwt:==========="+JsonUtil.getInstance().obj2json(jwt));
            if(a<=0) {
            	throw new UnauthorizedException("token 无效，请重新获取");
            }else if (a < JwtUtil.REFRESH_TOKEN_TIME) {
            	return false;//小于预警期
            };
            return true;
        } catch (JWTVerificationException exception) {
            throw new UnauthorizedException("token 无效，请重新获取");
        }
    }
    
    
    public static void main(String[] args) {
		String sign = sign("15919486546");
		System.out.println(sign);
		boolean checkSign = checkSign(sign);
		System.out.println(checkSign);
		
		String userId = getUserId(sign);
		System.out.println(userId);
		
	}
    
}